import { ElMessageBox } from 'element-plus'
import { setlocalStorage } from '@ve/utils/revocationPageInfo'
import dayjs from 'dayjs'
import { translateTitle } from '@/utils/i18n'
export default {
  data() {
    return {
      userId: '',
      appId: '',
      menuId: '',
      catchTaskInterval: '',
    }
  },
  mounted() {},
  beforeUnmount() {
    console.log('beforeUnmount')
    window.removeEventListener('popstate', this.back, false)
    window.removeEventListener('beforeunload', this.unload)
    // 清除定时器
    clearInterval(this.catchTaskInterval)
  },
  methods: {
    // 监听事件
    listenerFunction() {
      this.userId = this.$store.getters['user/uid']
      this.appId = this.$store.getters['user/appId']
      this.menuId = this.$route.query.ID || ''
      // 设置定时存储
      //缓存pageinfo
      this.catchTaskInterval = window.setInterval(() => {
        const pageInfoJson = this.$store.getters['diy/getPageInfo']
        pageInfoJson['TIMECODE'] = `${dayjs().format('YYYY-M-D HH:mm:ss')}`
        const catchJSON = JSON.stringify(pageInfoJson)
        // console.log('存储', catchJSON)
        //localStorage.setItem(`${this.userId}_${this.appId}_${this.menuId}`, catchJSON)
        //设置历史缓存
        setlocalStorage(this, catchJSON)
      }, 300000)
      // 监听后退方法
      if (window.history && window.history.pushState) {
        // 添加条件判断以解决当前页面刷新导致的错误添加 history 记录
        // console.log('history.state', history.state)
        if (history.state && history.state.back) {
          // console.log('添加记录')
          // 有 state 状态的话表示是由其他页面跳转至该页面 则添加空白记录以做用户提示用
          history.pushState(null, null, document.URL)
        }
        console.log('监听后退', history)
        window.addEventListener('popstate', this.back, false)
      }
      // 监听浏览器的刷新事件
      console.log('监听刷新')
      window.addEventListener('beforeunload', this.unload)
    },
    // 后退
    back() {
      // 判断是否有未保存拖拽记录
      // console.log('back----------' + `${this.userId}_${this.appId}_${this.menuId}`)
      const flag = localStorage.getItem(`${this.userId}_${this.appId}_${this.menuId}`)
      if (flag) {
        ElMessageBox.confirm(translateTitle('Ve.mixin.保存提示'), 'Warning', {
          confirmButtonText: translateTitle('Ve.utils.确认'),
          cancelButtonText: translateTitle('Ve.utils.取消'),
          type: 'warning',
        })
          .then(() => {
            this.$router.go(-1)
          })
          .catch(() => {
            if (window.history && window.history.pushState) {
              console.log('添加history记录')
              history.pushState(null, null, document.URL)
            }
          })
      }
    },
    unload(e) {
      e = e || window.event
      if (e) {
        // 在这里阻止默认的刷新，弹出弹框
        // 判断是否有未保存拖拽记录
        const flag = localStorage.getItem(`${this.userId}_${this.appId}_${this.menuId}`)
        if (flag) {
          e.returnValue = translateTitle('Ve.mixin.关闭提示')
        }
      }
      return translateTitle('Ve.mixin.关闭')
    },
  },
}
